package com.tjec.project.mobile.service.impl;

import com.tjec.common.constant.Constants;
import com.tjec.common.enums.NumCode;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.security.service.TokenService;
import com.tjec.framework.web.domain.TreeSelectNew;
import com.tjec.framework.web.domain.TreeSelectProjectDoc;
import com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeBusinessGuide;
import com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeCase;
import com.tjec.project.businessStandardLibrary.domain.BmsKnowledgePolicies;
import com.tjec.project.businessStandardLibrary.mapper.BmsKnowledgeBusinessGuideMapper;
import com.tjec.project.businessStandardLibrary.mapper.BmsKnowledgeCaseMapper;
import com.tjec.project.businessStandardLibrary.mapper.BmsKnowledgePoliciesMapper;
import com.tjec.project.businessStandardLibrary.service.IBmsKnowledgeBusinessGuideService;
import com.tjec.project.businessStandardLibrary.service.IBmsKnowledgeCaseService;
import com.tjec.project.businessWorkbench.domain.*;
import com.tjec.project.businessWorkbench.dto.BmsAttachmentDto;
import com.tjec.project.businessWorkbench.dto.BmsBusinessSketchDto;
import com.tjec.project.businessWorkbench.mapper.*;
import com.tjec.project.businessWorkbench.service.IBmsBusinessService;
import com.tjec.project.businessWorkbench.service.IBmsProjectDocCatalogService;
import com.tjec.project.businessWorkbench.service.IBmsProjectDocService;
import com.tjec.project.mobile.service.MobileService;
import com.tjec.project.portal.domain.BmsMsg;
import com.tjec.project.portal.domain.BmsNotes;
import com.tjec.project.portal.domain.BmsNotesStakeholder;
import com.tjec.project.portal.mapper.BmsMsgMapper;
import com.tjec.project.portal.mapper.BmsNotesMapper;
import com.tjec.project.portal.service.IBmsMsgService;
import com.tjec.project.portal.service.IBmsNotesStakeholderService;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsExpertPerson;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsLeaderMember;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsMdExpertType;
import com.tjec.project.projectLeaderWorkbeanch.mapper.BmsExpertPersonMapper;
import com.tjec.project.projectLeaderWorkbeanch.mapper.BmsLeaderMemberMapper;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsLeaderMemberService;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsMdExpertTypeService;
import com.tjec.project.projectWorkbench.domain.*;
import com.tjec.project.projectWorkbench.mapper.BmsProjectMapper;
import com.tjec.project.projectWorkbench.mapper.BmsProjectMemberMapper;
import com.tjec.project.projectWorkbench.mapper.BmsProjectStakeholderMapper;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberService;
import com.tjec.project.system.domain.*;
import com.tjec.project.system.mapper.*;
import com.tjec.project.system.service.IBmsMdAreaService;
import com.tjec.project.system.service.IBmsMdBusinessCategoryService;
import com.tjec.project.system.service.ISysRoleService;
import com.tjec.project.system.service.ISysUserService;
import com.tjec.project.workflow.domain.BmsWorkflow;
import com.tjec.project.workflow.mapper.BmsWorkflowMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：cjj
 * @date ：Created in 2020/8/17 15:01
 */
@Service
public class MobileServiceImpl implements MobileService {

    @Autowired
    private BmsMsgMapper bmsMsgMapper;

    @Autowired
    private BmsNotesMapper bmsNotesMapper;

    @Autowired
    private BmsKnowledgeBusinessGuideMapper bmsKnowledgeBusinessGuideMapper;

    @Autowired
    private BmsKnowledgeCaseMapper bmsKnowledgeCaseMapper;

    @Autowired
    private BmsKnowledgePoliciesMapper bmsKnowledgePoliciesMapper;

    @Autowired
    private BmsProjectMapper bmsProjectMapper;

    @Autowired
    private BmsLeaderMemberMapper bmsLeaderMemberMapper;

    @Autowired
    private IBmsMdAreaService bmsMdAreaService;

    @Autowired
    private IBmsBusinessService bmsBusinessService;

    @Autowired
    private BmsProjectMemberMapper bmsProjectMemberMapper;

    @Autowired
    private BmsProjectStakeholderMapper bmsProjectStakeholderMapper;

    @Autowired
    private BmsBusinessMapper bmsBusinessMapper;

    @Autowired
    private BmsBusinessSketchMapper bmsBusinessSketchMapper;

    @Autowired
    private BmsBusinessPickupMapper bmsBusinessPickupMapper;

    @Autowired
    private BmsProjectDocMapper bmsProjectDocMapper;

    @Autowired
    private IBmsProjectDocCatalogService bmsProjectDocCatalogService;

    @Autowired
    private BmsWorkflowMapper bmsWorkflowMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private IBmsMsgService bmsMsgService;

    @Autowired
    private IBmsLeaderMemberService bmsLeaderMemberService;

    @Autowired
    private BmsMdBusinessCategoryMapper bmsMdBusinessCategoryMapper;

    @Autowired
    private IBmsKnowledgeBusinessGuideService bmsKnowledgeBusinessGuideService;

    @Autowired
    private IBmsKnowledgeCaseService bmsKnowledgeCaseService;

    @Autowired
    private BmsMdAreaMapper bmsMdAreaMapper;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private BmsExpertPersonMapper bmsExpertPersonMapper;

    @Autowired
    private IBmsMdExpertTypeService bmsMdExpertTypeService;

    @Autowired
    private BmsProjectDocCatalogMapper bmsProjectDocCatalogMapper;

    @Autowired
    private BmsBusinessDocArchiveMapper bmsBusinessDocArchiveMapper;

    @Autowired
    private IBmsProjectDocService bmsProjectDocService;

    @Autowired
    private IBmsProjectMemberService bmsProjectMemberService;

    @Autowired
    private BmsAttachmentMapper bmsAttachmentMapper;

    @Autowired
    private BmsMdIndustryCategoryMapper bmsMdIndustryCategoryMapper;

    @Autowired
    private IBmsMdBusinessCategoryService bmsMdBusinessCategoryService;

    @Autowired
    private IBmsNotesStakeholderService iBmsNotesStakeholderService;

    @Value("${sftp.http}")
    private String http;
    @Value("${sftp.ip}")
    private String ip;

    /**
     * 我的消息列表-移动端
     * @param bmsMsg
     * @return
     */
    @Override
    public List<BmsMsg> selectBmsMsgMobileList(BmsMsg bmsMsg) {
        bmsMsg.setReceiverUserId(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        return bmsMsgMapper.selectBmsMsgMobileList(bmsMsg);
    }

    /**
     * 我的便签列表-移动端
     * @param bmsNotes
     * @return
     */
    @Override
    public List<BmsNotes> selectBmsNotesMobileList(BmsNotes bmsNotes) {
        bmsNotes.setCreateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        List<BmsNotes> list = bmsNotesMapper.selectBmsNotesMobileList(bmsNotes);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(item -> {
                BmsNotesStakeholder bmsNotesStakeholder = new BmsNotesStakeholder();
                bmsNotesStakeholder.setNotesId(item.getGuid());
                item.setStakeholderList(iBmsNotesStakeholderService.selectBmsNotesStakeholderList(bmsNotesStakeholder));
            });
        }
        return list;
    }

    /**
     * 业务手册列表-移动端
     * @param bmsKnowledgeBusinessGuide
     * @return
     */
    @Override
    public List<BmsKnowledgeBusinessGuide> selectBmsKnowledgeBusinessGuideMobileList(BmsKnowledgeBusinessGuide bmsKnowledgeBusinessGuide) {
        List<BmsKnowledgeBusinessGuide> lists = bmsKnowledgeBusinessGuideMapper.selectBmsKnowledgeBusinessGuideMobileList(bmsKnowledgeBusinessGuide);
        for(BmsKnowledgeBusinessGuide list : lists) {
            list.setContentSize(getFileSize(list.getContentLength()));
            if(list!=null&& StringUtils.isNotBlank(list.getStoragePath())){
                list.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + list.getStoragePath());
            }
        }
        return lists;
    }

    /**
     * 业务手册列表-移动端
     * @param bmsKnowledgeBusinessGuide
     * @return
     */
    /*@Override
    public List<BmsKnowledgeBusinessGuide> selectBmsKnowledgeBusinessGuideMobileList(BmsKnowledgeBusinessGuide bmsKnowledgeBusinessGuide) {
        String businessCategoryId=bmsKnowledgeBusinessGuide.getBusinessCategoryId();
        List<String> ids=new ArrayList<>();
        List<BmsKnowledgeBusinessGuide> bms=new ArrayList<>();
        //业务树查询
        if(StringUtils.isNotBlank(businessCategoryId)){
            //获取业务层级
            int level = bmsKnowledgeBusinessGuideService.businessLevel(businessCategoryId);

            if(level== CodeNum.ONE.getCode()){
                //第一层
                ids= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryChildIdsOne(businessCategoryId);
            }else if(level==CodeNum.TWO.getCode()){
                //第二层
                ids= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryChildIdsTwo(businessCategoryId);
            }else {
                //第三层
                ids.add(businessCategoryId);
            }
            //没有第三层的问题
            if(ids.isEmpty()){
                ids.add(businessCategoryId);
            }
            bmsKnowledgeBusinessGuide.setGuIds(ids);
            bms=bmsKnowledgeBusinessGuideMapper.selectBmsKnowledgeBusinessGuideMobileList(bmsKnowledgeBusinessGuide);
        }else {
            //不点业务树查询
            bms= bmsKnowledgeBusinessGuideMapper.selectBmsKnowledgeBusinessGuideMobileList(bmsKnowledgeBusinessGuide);

        }
        for (BmsKnowledgeBusinessGuide knowledgeBusinessGuide : bms) {
            if(knowledgeBusinessGuide!=null&& StringUtils.isNotBlank(knowledgeBusinessGuide.getStoragePath())){
                knowledgeBusinessGuide.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + knowledgeBusinessGuide.getStoragePath());
            }
        }
        return bms;
    }*/
    /**
     * 典型案例列表-移动端
     *
     * @param bmsKnowledgeCase
     * @return
     */
    @Override
    public List<BmsKnowledgeCase> selectBmsKnowledgeCaseMobileList(BmsKnowledgeCase bmsKnowledgeCase) {
        List<BmsKnowledgeCase> bms = bmsKnowledgeCaseMapper.selectBmsKnowledgeCaseMobileList(bmsKnowledgeCase);
        for (BmsKnowledgeCase knowledgeCase : bms) {
            if (!org.springframework.util.CollectionUtils.isEmpty(knowledgeCase.getAttachments())) {
                for (BmsAttachment bmsAttachment : knowledgeCase.getAttachments()) {
                    if (bmsAttachment != null && StringUtils.isNotBlank(bmsAttachment.getStoragePath())) {
                        bmsAttachment.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
                    }
                }
            }
        }
        return bms;
    }

    /**
     * 典型案例列表-移动端
     *
     * @param bmsKnowledgeCase
     * @return
     */
    /*@Override
    public List<BmsKnowledgeCase> selectBmsKnowledgeCaseMobileList(BmsKnowledgeCase bmsKnowledgeCase) {
        String businessCategoryId=bmsKnowledgeCase.getBusinessCategoryId();
        List<String> lists = bmsKnowledgeCase.getCitys();
        if(lists==null||lists.equals("")||lists.isEmpty()){

        }else {
            bmsKnowledgeCase.setProvince(bmsMdAreaMapper.selectBmsMdAreaByGuid(lists.get(0)).getCname());
            if(lists.size()>1) {
                bmsKnowledgeCase.setCity(bmsMdAreaMapper.selectBmsMdAreaByGuid(lists.get(1)).getCname());
            }
        }
        List<String> ids=new ArrayList<>();;
        List<BmsKnowledgeCase> bms=new ArrayList<>();
        int level = 0;
        //业务树查询
        if(StringUtils.isNotBlank(businessCategoryId)){
            level = bmsKnowledgeBusinessGuideService.businessLevel(businessCategoryId);

            if(level==CodeNum.ONE.getCode()){
                ids= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryChildIdsOne(businessCategoryId);
            }else if(level==CodeNum.TWO.getCode()){
                //对于只有两级的问题
                ids= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryChildIdsTwo(businessCategoryId);
            }else {
                ids.add(businessCategoryId);
            }
            //没有第三层的问题
            if(ids.isEmpty()){
                ids.add(businessCategoryId);
            }
            bmsKnowledgeCase.setGuids(ids);
            bms=bmsKnowledgeCaseMapper.selectBmsKnowledgeCaseMobileList(bmsKnowledgeCase);
        }else {
            //不点业务树查询
            // bms=bmsKnowledgeCaseMapper.selectBmsKnowledgeCaseListNoTree(bmsKnowledgeCase);
            bms=bmsKnowledgeCaseMapper.selectBmsKnowledgeCaseMobileList(bmsKnowledgeCase);
        }
        if(ids.size()==1) {
            bms = bmsKnowledgeCaseService.bmsKnowledgeCaseList(bms,businessCategoryId);
        }else {
            bms = bmsKnowledgeCaseService.bmsKnowledgeCaseList(bms);
        }
        for (BmsKnowledgeCase knowledgeCase : bms) {
            if (!org.springframework.util.CollectionUtils.isEmpty(knowledgeCase.getAttachments())) {
                for (BmsAttachment bmsAttachment : knowledgeCase.getAttachments()) {
                    if (bmsAttachment != null && StringUtils.isNotBlank(bmsAttachment.getStoragePath())) {
                        bmsAttachment.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
                    }
                }
            }
        }
        return bms;
    }*/

    /**
     *法规导航列表-移动端
     *
     * @param bmsKnowledgePolicies
     * @return
     */
    @Override
    public List<BmsKnowledgeCase> selectBmsKnowledgePoliciesMobileList(BmsKnowledgePolicies bmsKnowledgePolicies) {
        return bmsKnowledgePoliciesMapper.selectBmsKnowledgePoliciesMobileList(bmsKnowledgePolicies);
    }

    /**
     * 项目清单列表-移动端
     *
     * @param bmsProject
     * @return
     */
    @Override
    public List<BmsProject> selectBmsProjectMobileList(BmsProject bmsProject) {
        return bmsProjectMapper.selectBmsProjectMobileList(bmsProject);
    }

    /**
     *  人员清单列表-移动端
     *
     * @param bmsLeaderMember
     * @return
     */
    @Override
    public List<BmsLeaderMember> selectBmsLeaderMemberMobileList(BmsLeaderMember bmsLeaderMember) {
        return bmsLeaderMemberMapper.selectBmsLeaderMemberMobileList(bmsLeaderMember);
    }

    /**
     * 项目概况-移动端
     *
     * @param guid
     * @return
     */
    @Override
    public BmsProject selectBmsProjectByGuidMobile(String guid) {
        BmsProject bmsProject = bmsProjectMapper.selectBmsProjectByGuidMobile(guid);
        if (null != bmsProject) {
            String link = bmsProject.getLink();
            List<Map<String, Object>> linkList = new ArrayList<>();
            if (StringUtils.isNotBlank(link)) {
                String[] strLink = link.split(";");
                for (String str : strLink) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("linkName", str.split(",")[0]);
                    map.put("linkUrl", str.split(",")[1]);
                    linkList.add(map);
                }
                bmsProject.setLinkArray(linkList);
            }
            if(StringUtils.isNotBlank(bmsProject.getArea())){
                String[] areas = bmsProject.getArea().split(";");
                bmsProject.setAreas(areas);
                List<BmsMdArea> bmsMdAreas = bmsMdAreaService.selectBmsMdAreaByGuids(areas);
                String areaName = "";
                if(!CollectionUtils.isEmpty(bmsMdAreas)){
                    for (int i = 0; i < bmsMdAreas.size(); i++) {
                        if(i == bmsMdAreas.size()-1){
                            areaName += bmsMdAreas.get(i).getCname();
                        }else{
                            areaName += bmsMdAreas.get(i).getCname()+" / ";
                        }
                    }
                }
                bmsProject.setAreaName(areaName);
            }
            if(StringUtils.isNotBlank(bmsProject.getIndustry())){
                String[] industrys = bmsProject.getIndustry().split(";");
                bmsProject.setIndustrys(industrys);
                String industryName = "";
                for (int i = 0; i < industrys.length; i++) {
                    BmsMdIndustryCategory bmsMdIndustryCategory = bmsMdIndustryCategoryMapper.selectBmsMdIndustryCategoryByGuid(industrys[i]);
                    if(i == industrys.length-1){
                        industryName += bmsMdIndustryCategory.getCname();
                    }else{
                        industryName += bmsMdIndustryCategory.getCname()+",";
                    }
                }
                bmsProject.setIndustry(industryName);
            }
            //获取该项目所有业务名称并去重
            BmsBusiness bmsBusiness = new BmsBusiness();
            bmsBusiness.setProjectId(bmsProject.getGuid());
            List<BmsBusiness> list = bmsBusinessService.selectBmsBusinessList(bmsBusiness);
            Set<String> businessCategory = new HashSet<>();
            for (BmsBusiness business : list) {
                businessCategory.add(business.getMenuName());
            }
            bmsProject.setBusinessCategory(StringUtils.strip(businessCategory.toString(), "[]"));
            if(!CollectionUtils.isEmpty(bmsProject.getBmsAttachments())){
                for (BmsAttachment bmsAttachment : bmsProject.getBmsAttachments()) {
                    bmsAttachment.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
                }
            }
        }
        return bmsProject;
    }

    /**
     * 项目成员-移动端
     *
     * @param bmsProjectMember
     * @return
     */
    @Override
    public List<BmsProjectMember> selectBmsProjectMemberMobileList(BmsProjectMember bmsProjectMember) {
        return bmsProjectMemberMapper.selectBmsProjectMemberMobileList(bmsProjectMember);
    }

    /**
     * 查询项目干系人-移动端
     *
     * @param bmsProjectStakeholder
     * @return
     */
    @Override
    public List<BmsProjectStakeholder> selectBmsProjectStakeholderMobileList(BmsProjectStakeholder bmsProjectStakeholder) {
        return bmsProjectStakeholderMapper.selectBmsProjectStakeholderMobileList(bmsProjectStakeholder);
    }

    /**
     * 查询业务清单-移动端
     *
     * @param bmsBusiness
     * @return
     */
    @Override
    public List<BmsBusiness> selectBmsBusinessMobileList(BmsBusiness bmsBusiness) {
        return bmsBusinessMapper.selectBmsBusinessMobileList(bmsBusiness);
    }

    /**
     * 业务概况-移动端
     *
     * @param businessId
     * @return
     */
    @Override
    public BmsBusinessSketchDto getBusinessSketchMobile(String businessId) {
        return bmsBusinessSketchMapper.getBusinessSketchMobile(businessId);
    }

    /**
     * 收资管理列表-移动端
     *
     * @param bmsBusinessPickup
     * @return
     */
    @Override
    public List<BmsBusinessPickup> selectBmsBusinessPickupMobileList(BmsBusinessPickup bmsBusinessPickup) {
        return bmsBusinessPickupMapper.selectBmsBusinessPickupMobileList(bmsBusinessPickup);
    }
    /**
     * 项目文档目录-移动端（懒加载）
     *
     * @param bmsProjectDoc
     * @return
     */
    @Override
    public Map<String,Object> lazyBuildDocCatalogTreeSelectMobile(BmsProjectDoc bmsProjectDoc) {
        Map<String,Object> map = new HashMap<>();
        List<BmsAttachment> attachments = new ArrayList<>();
        String businessId = bmsProjectDoc.getBusinessId();
        String catalogId = bmsProjectDoc.getCatalogId();
        if(StringUtils.isBlank(businessId)){
            return map;
        }
        List<TreeSelectProjectDoc> trees = new ArrayList<>();
        BmsProjectDocCatalog bmsProjectDocCatalog = new BmsProjectDocCatalog();
        if(StringUtils.isBlank(catalogId)){
            bmsProjectDocCatalog.setParentId("0");
        }else{
            bmsProjectDocCatalog.setParentId(catalogId);
        }
        bmsProjectDocCatalog.setBusinessId(businessId);
        bmsProjectDocCatalog.setSearchValue(bmsProjectDoc.getSearchValue());

        //目录对应子目录
        List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogMobileList(bmsProjectDocCatalog);
        //根目录数据统计
        if(!CollectionUtils.isEmpty(bmsProjectDocCatalogs)&&StringUtils.isBlank(catalogId)){
            BmsProjectDocCatalog bmsProjectDocCatalogRoot = new BmsProjectDocCatalog();
            bmsProjectDocCatalogRoot.setParentId(bmsProjectDocCatalogs.get(0).getGuid());
            bmsProjectDocCatalogRoot.setBusinessId(businessId);
            List<BmsProjectDocCatalog> bmsProjectDocCatalogCount = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogMobileList(bmsProjectDocCatalogRoot);
            bmsProjectDocCatalogs.get(0).setCounts(counts(bmsProjectDocCatalogCount, businessId));
            //非根目录数据统计
        }else{
            counts(bmsProjectDocCatalogs, businessId);
        }
        List<TreeSelectProjectDoc> bmsProjectDocCatalogTrees = bmsProjectDocCatalogs.stream().map(TreeSelectProjectDoc::new).collect(Collectors.toList());
        trees.addAll(bmsProjectDocCatalogTrees);

        //目录下附件名称
        if(StringUtils.isNotBlank(bmsProjectDoc.getCatalogId())){
            BmsProjectDocCatalog item = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogByGuid(catalogId);
            if(item!=null&&StringUtils.isNotBlank(item.getParentId())&&!item.getParentId().equals("0")){
                //收资管理
                if("0".equals(item.getIsEdit())) {
                    List<BmsBusinessPickup> bmsBusinessPickups = bmsBusinessPickupMapper.getPickupAttByGuid(businessId);
                    if(!CollectionUtils.isEmpty(bmsBusinessPickups)){
                        List<TreeSelectProjectDoc> bmsBusinessPickupTrees = bmsBusinessPickups.stream().map(TreeSelectProjectDoc::new).collect(Collectors.toList());
                        trees.addAll(bmsBusinessPickupTrees);
                        attachments = bmsAttachmentMapper.selectBmsAttachmentByBizIdsModel(bmsBusinessPickups.stream().map(BmsBusinessPickup::getGuid).collect(Collectors.toList()));
                    }
                    //项目文档
                }else if("1".equals(item.getIsEdit())) {
                    List<BmsProjectDoc> bmsProjectDocs = bmsProjectDocMapper.getDocAttByCatalogId(catalogId);
                    List<TreeSelectProjectDoc> bmsProjectDocTrees = bmsProjectDocs.stream().map(TreeSelectProjectDoc::new).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(bmsProjectDocTrees)){
                        trees.addAll(bmsProjectDocTrees);
                        List<String> attId = bmsProjectDocs.stream().map(BmsProjectDoc::getGuid).collect(Collectors.toList());
                        attachments = bmsAttachmentMapper.selectBmsAttachmentByBizIdsModel(attId);
                    }
                    //归档资料
                }else if("2".equals(item.getIsEdit())) {
                    List<BmsBusinessDocArchive> bmsBusinessDocArchives = bmsBusinessDocArchiveMapper.selectBmsBusinessDocArchiveListAttByBusinessId(businessId);
                    if(!CollectionUtils.isEmpty(bmsBusinessDocArchives)){
                        List<TreeSelectProjectDoc> bmsBusinessDocArchiveTrees = bmsBusinessDocArchives.stream().map(TreeSelectProjectDoc::new).collect(Collectors.toList());
                        trees.addAll(bmsBusinessDocArchiveTrees);
                        attachments = bmsAttachmentMapper.selectBmsAttachmentByBizIdsModel(bmsBusinessDocArchives.stream().map(BmsBusinessDocArchive::getGuid).collect(Collectors.toList()));
                    }
                    //成果校审
                }else if("3".equals(item.getIsEdit())) {
                    attachments = bmsAttachmentMapper.selectBmsAttachmentByBizId(item.getGuid());
                }
            }
        }
        attachments.forEach(it -> {
            if (StringUtils.isNotBlank(it.getGuid())) {
                it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
            }
        });
        map.put("catalogs",trees);
        map.put("attachments",attachments);
        return map;
    }


    /**
     * 项目文档目录-移动端
     *
     * @param bmsProjectDocCatalog
     * @return
     */
    @Override
    public List<TreeSelectNew> buildDocCatalogTreeSelectMobile(BmsProjectDocCatalog bmsProjectDocCatalog) {
        Map<String,String> map = new HashMap<String,String>();
        map.put("businessId", bmsProjectDocCatalog.getBusinessId());
        List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocCatalogService
                .selectBmsProjectDocCatalogList(bmsProjectDocCatalog);
        if (bmsProjectDocCatalogs != null && bmsProjectDocCatalogs.size() > 0) {
            bmsProjectDocCatalogs.forEach(item -> {
                if(item.getParentId().equals("0")){
                    Integer pickUpCounts = bmsProjectDocCatalogService.selectPickUpCounts(map.get("businessId"));
                    Integer docCounts = bmsProjectDocCatalogService.selectDocCounts(item.getGuid());
                    Integer archiveCounts = bmsProjectDocCatalogService.selectArchiveCounts(map.get("businessId"));
                    Integer resultCounts = bmsProjectDocCatalogService.selectResultCounts(item.getGuid());
                    item.setCounts(pickUpCounts+docCounts+archiveCounts+resultCounts);
                    item.setIsEdit(null);
                }else{
                    if("0".equals(item.getIsEdit())) {
                        Integer res = bmsProjectDocCatalogService.selectPickUpCounts(map.get("businessId"));
                        item.setCounts(res == null ? 0 : res);
                    }else if("1".equals(item.getIsEdit())) {
                        Integer res = bmsProjectDocCatalogService.selectDocCounts(item.getGuid());
                        item.setCounts(res == null ? 0 : res);
                    }else if("2".equals(item.getIsEdit())) {
                        Integer res = bmsProjectDocCatalogService.selectArchiveCounts(map.get("businessId"));
                        item.setCounts(res == null ? 0 : res);
                    }else if("3".equals(item.getIsEdit())) {
                        Integer res = bmsProjectDocCatalogService.selectResultCounts(item.getGuid());
                        item.setCounts(res == null ? 0 : res);
                    }
                }
            });
        }
        return bmsProjectDocCatalogService.buildDocCatalogTreeSelect(bmsProjectDocCatalogs);
    }

    /**
     * 项目文档详情-移动端
     *
     * @param bmsProjectDoc
     * @return
     */
    @Override
    public List<BmsProjectDoc> selectAllProjectDocQueryMobileList(BmsProjectDoc bmsProjectDoc) {
        List<BmsProjectDoc> list = bmsProjectDocMapper.selectAllProjectDocQueryMobileList(bmsProjectDoc);
        list.forEach(item -> {
            List<BmsAttachmentDto> attachments = item.getAttachments();
            attachments.forEach(it -> {
                if (StringUtils.isNotBlank(it.getFileId())) {
                    it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                }
            });
        });
        return list;
    }

    @Override
    public List<BmsWorkflow> selectBmsWorkflowMobileList(BmsWorkflow bmsWorkflow) {
        if (bmsWorkflow.getType() == null || "".equals(bmsWorkflow.getType())) {
            // 当前登陆人工号
            String jobNo = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getJobNo();
            // 当前登陆人id
            String userId = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId();

            bmsWorkflow.setStartPerson(jobNo);
            bmsWorkflow.setApprovePerson(jobNo);
        }
        return bmsWorkflowMapper.selectBmsWorkflowMobileList(bmsWorkflow);
    }

    /**
     * 项目工作台列表-移动端
     *
     * @param bmsProject
     * @return
     */
    @Override
    public List<BmsProject> selectBmsProjectGlanceMobileList(BmsProject bmsProject) {
        return bmsProjectMapper.selectBmsProjectGlanceMobileList(bmsProject);
    }

    /**
     * 是否为项目负责人或项目负责人工作台管理员
     *
     * @param userId
     * @return
     */
    @Override
    public boolean isProjectLeader(String userId) {
        boolean flag = false;
        List<SysRole> list = sysRoleMapper.selectRolePermissionByUserId(userId);
        if(CollectionUtils.isEmpty(list)){
            return false;
        }
        for (SysRole role : list) {
            if(role.getRoleKey().equals(Constants.ROLE_PROJECT_LEADER_KEY)||role.getRoleKey().equals(Constants.ROLE_PROJECT_LEADER_WORKBENCH_ADMIN_KEY)){
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 消息批量已读
     *
     * @return
     */
    @Override
    public int myMessageBatchRead() {
        BmsMsg bmsMsg = new BmsMsg();
        String guid = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId();
        bmsMsg.setReceiverUserId(guid);
        bmsMsg.setStatus(NumCode.ONE.getCode());
        return bmsMsgService.batchRead(bmsMsg);
    }

    /**
     * 授权管理员列表
     * @param bmsLeaderMember
     * @return
     */
    @Override
    public List<BmsLeaderMember> selectBmsLeaderMemberList(BmsLeaderMember bmsLeaderMember) {
        List<BmsLeaderMember> list = bmsLeaderMemberService.selectBmsLeaderMemberLeaderList(bmsLeaderMember);
        if(StringUtils.isNotBlank(bmsLeaderMember.getUserId())&&sysRoleService.isExistRoleByUserId(Constants.ROLE_PROJECT_LEADER_KEY, bmsLeaderMember.getUserId())){
            BmsLeaderMember leaderMember = new BmsLeaderMember();
            leaderMember.setUserId(bmsLeaderMember.getUserId());
            SysUser sysUser = sysUserService.selectUserById(bmsLeaderMember.getUserId());
            leaderMember.setNickName(sysUser.getNickName());
            leaderMember.setLeader(bmsLeaderMember.getUserId());
            leaderMember.setJobNo(sysUser.getJobNo());
            list.add(leaderMember);
        }
        return list;
    }

    /**
     * 专家清单列表
     * @param bmsExpertPerson
     * @return
     */
    @Override
    public List<BmsExpertPerson> selectBmsExpertPersonMobileList(BmsExpertPerson bmsExpertPerson) {
        List<BmsExpertPerson> list = bmsExpertPersonMapper.selectBmsExpertPersonMobileList(bmsExpertPerson);
        for (BmsExpertPerson expertPerson : list) {
            if(expertPerson == null){
                continue;
            }
            if(StringUtils.isNotBlank(expertPerson.getProfessionCategory())){
                List<BmsMdExpertType> professionCategoryExpertType = bmsMdExpertTypeService.selectBmsMdExpertTypeByGuids(expertPerson.getProfessionCategory().split(";"));
                String professionCategoryNames = "";
                for (BmsMdExpertType bmsMdExpertType : professionCategoryExpertType) {
                    professionCategoryNames += bmsMdExpertType.getCname()+";";
                }
                expertPerson.setProfessionCategoryName(professionCategoryNames);
            }
            if(StringUtils.isNotBlank(expertPerson.getProfessionCategory())){
                expertPerson.setProfessionCategorys( expertPerson.getProfessionCategory().split(";"));
            }
            if(StringUtils.isNotBlank(expertPerson.getBusinessMerit())){
                expertPerson.setBusinessMerits( expertPerson.getBusinessMerit().split(";"));
            }
            if(StringUtils.isNotBlank(expertPerson.getIndustryMerit())){
                expertPerson.setIndustryMerits( expertPerson.getIndustryMerit().split(";"));
            }
            if(!org.springframework.util.CollectionUtils.isEmpty(expertPerson.getBmsAttachments())){
                ArrayList<String> attIds = new ArrayList<>();
                for (BmsAttachment bmsAttachment : expertPerson.getBmsAttachments()) {
                    bmsAttachment.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
                    attIds.add(bmsAttachment.getGuid());
                }
                expertPerson.setAttachmentIds(attIds);
            }
        }
        return list;
    }

    /**
     * 项目主页文档查询树-移动端
     * @param bmsProjectDoc
     * @return
     */
    @Override
    public Map<String, Object> lazyBuildFileQueryTreeMobile(BmsProjectDoc bmsProjectDoc) {
        Map<String,Object> map = new HashMap<>();
        List<BmsAttachment> attachments = new ArrayList<>();
        String projectId = bmsProjectDoc.getProjectId();
        String businessId = bmsProjectDoc.getBusinessId();
        String catalogId = bmsProjectDoc.getCatalogId();
        String level = bmsProjectDoc.getLevel();
        if(StringUtils.isBlank(projectId)){
            return map;
        }
        List<TreeSelectProjectDoc> trees = new ArrayList<>();
        //初始化参数
        BmsProjectDocCatalog bmsProjectDocCatalog = new BmsProjectDocCatalog();
        bmsProjectDocCatalog.setProjectId(projectId);
        bmsProjectDocCatalog.setBusinessId(businessId);
        bmsProjectDocCatalog.setParentId(catalogId);
        bmsProjectDocCatalog.setSearchValue(bmsProjectDoc.getSearchValue());
        if(StringUtils.isNotBlank(catalogId)){
            BmsProjectDocCatalog pdclog = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogByGuid(catalogId);
            bmsProjectDocCatalog.setBusinessId(pdclog!=null?pdclog.getBusinessId():null);
            businessId = pdclog!=null?pdclog.getBusinessId():null;
        }
        //根目录或初始化
        if(StringUtils.isBlank(catalogId)&&StringUtils.isBlank(businessId)&&(StringUtils.isBlank(level)||level.equals("0"))){
            BmsProject bmsProject = selectBmsProjectByGuidMobile(projectId);
            TreeSelectProjectDoc tree = new TreeSelectProjectDoc();
            tree.setId(bmsProject.getGuid());
            tree.setLabel(bmsProject.getName());
            bmsProjectDoc.setCatalogId(projectId);
            bmsProjectDocService.parsingParamBmsProjectDoc(bmsProjectDoc);
            tree.setCounts(bmsProjectDocService.countProjectDocCatalog(bmsProjectDoc));
            trees.add(tree);
            //二级目录
        }else if(bmsProjectDoc.getLevel().equals("1")) {
            bmsProjectDocCatalog.setParentId("0");
            List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogMobileList(bmsProjectDocCatalog);
            if (bmsProjectDocCatalogs != null && bmsProjectDocCatalogs.size() > 0) {
                bmsProjectDocCatalogs.forEach(item -> {
                    bmsProjectDoc.setCatalogId(item.getGuid());
                    bmsProjectDocService.parsingParamBmsProjectDoc(bmsProjectDoc);
                    item.setCounts(bmsProjectDocService.countProjectDocCatalog(bmsProjectDoc));
                });
            }
            List<TreeSelectProjectDoc> bmsProjectDocCatalogTrees = bmsProjectDocCatalogs.stream().map(TreeSelectProjectDoc::new).collect(Collectors.toList());
            trees.addAll(bmsProjectDocCatalogTrees);
            //二级以下目录
        }else{
            if(StringUtils.isBlank(catalogId)){
                bmsProjectDocCatalog.setParentId("0");
            }else{
                bmsProjectDocCatalog.setParentId(catalogId);
            }
            //目录对应子目录
            bmsProjectDoc.setBusinessId(businessId);
            List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocService.getProjectDocCatalogChildren(bmsProjectDoc);
//            List<BmsProjectDocCatalog> bmsProjectDocCatalogs = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogMobileList(bmsProjectDocCatalog);
            //根目录数据统计
            if(!CollectionUtils.isEmpty(bmsProjectDocCatalogs)&&StringUtils.isBlank(catalogId)){
                BmsProjectDocCatalog bmsProjectDocCatalogRoot = new BmsProjectDocCatalog();
                bmsProjectDocCatalogRoot.setParentId(bmsProjectDocCatalogs.get(0).getGuid());
                bmsProjectDocCatalogRoot.setBusinessId(businessId);
                List<BmsProjectDocCatalog> bmsProjectDocCatalogCount = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogMobileList(bmsProjectDocCatalogRoot);
                Integer rootCount = 0;
                bmsProjectDocCatalogs.get(0).setCounts(counts(bmsProjectDocCatalogCount, businessId));
                //非根目录数据统计
            }else{
//                counts(bmsProjectDocCatalogs, businessId);
            }
            List<TreeSelectProjectDoc> bmsProjectDocCatalogTrees = bmsProjectDocCatalogService.buildDocCatalogTreeSelectProjectDoc(bmsProjectDocCatalogs);
            trees.addAll(bmsProjectDocCatalogTrees);

            //目录下附件名称
            if(StringUtils.isNotBlank(bmsProjectDoc.getCatalogId())){
                BmsProjectDocCatalog item = bmsProjectDocCatalogMapper.selectBmsProjectDocCatalogByGuid(catalogId);
                if(item!=null&&StringUtils.isNotBlank(item.getParentId())&&!item.getParentId().equals("0")){
                    //收资管理
                    if("0".equals(item.getIsEdit())) {
                        List<BmsBusinessPickup> bmsBusinessPickups = bmsBusinessPickupMapper.getPickupAttByGuid(businessId);
                        if(!CollectionUtils.isEmpty(bmsBusinessPickups)){
                            List<TreeSelectProjectDoc> bmsBusinessPickupTrees = bmsBusinessPickups.stream().map(TreeSelectProjectDoc::new).collect(Collectors.toList());
                            trees.addAll(bmsBusinessPickupTrees);
                            attachments = bmsAttachmentMapper.selectBmsAttachmentByBizIdsModel(bmsBusinessPickups.stream().map(BmsBusinessPickup::getGuid).collect(Collectors.toList()));
                        }
                        //项目文档
                    }else if("1".equals(item.getIsEdit())) {
                        List<BmsProjectDoc> bmsProjectDocs = bmsProjectDocMapper.getDocAttByCatalogId(catalogId);
                        List<TreeSelectProjectDoc> bmsProjectDocTrees = bmsProjectDocs.stream().map(TreeSelectProjectDoc::new).collect(Collectors.toList());
                        if(!CollectionUtils.isEmpty(bmsProjectDocTrees)){
                            trees.addAll(bmsProjectDocTrees);
                            List<String> attId = bmsProjectDocs.stream().map(BmsProjectDoc::getGuid).collect(Collectors.toList());
                            attachments = bmsAttachmentMapper.selectBmsAttachmentByBizIdsModel(attId);
                        }
                        //归档资料
                    }else if("2".equals(item.getIsEdit())) {
                        List<BmsBusinessDocArchive> bmsBusinessDocArchives = bmsBusinessDocArchiveMapper.selectBmsBusinessDocArchiveListAttByBusinessId(businessId);
                        if(!CollectionUtils.isEmpty(bmsBusinessDocArchives)){
                            List<TreeSelectProjectDoc> bmsBusinessDocArchiveTrees = bmsBusinessDocArchives.stream().map(TreeSelectProjectDoc::new).collect(Collectors.toList());
                            trees.addAll(bmsBusinessDocArchiveTrees);
                            attachments = bmsAttachmentMapper.selectBmsAttachmentByBizIdsModel(bmsBusinessDocArchives.stream().map(BmsBusinessDocArchive::getGuid).collect(Collectors.toList()));
                        }
                        //成果校审
                    }else if("3".equals(item.getIsEdit())) {
                        attachments = bmsAttachmentMapper.selectBmsAttachmentByBizId(item.getGuid());
                    }
                }
            }
            attachments.forEach(it -> {
                if (StringUtils.isNotBlank(it.getGuid())) {
                    it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
                }
            });
        }
        map.put("catalogs", trees);
        map.put("attachments",attachments);
        return map;
    }

    public Integer counts(List<BmsProjectDocCatalog> bmsProjectDocCatalogCount, String businessId){
        if(StringUtils.isBlank(businessId)){
            businessId = bmsProjectDocCatalogCount.get(0).getBusinessId();
        }
        Integer total = 0;
        Integer pickUpRes = bmsProjectDocCatalogMapper.selectPickUpSimpleCounts(businessId);
        total += pickUpRes;
        Integer archiveRes = bmsProjectDocCatalogMapper.selectArchiveSimpleCounts(businessId);
        total += archiveRes;
        for (BmsProjectDocCatalog item : bmsProjectDocCatalogCount) {
            if("0".equals(item.getIsEdit())){
                item.setCounts(pickUpRes);
            }
            if("2".equals(item.getIsEdit())){
                item.setCounts(archiveRes);
            }
            if("1".equals(item.getIsEdit())){
                Integer res = bmsProjectDocCatalogMapper.selectDocSimpleCounts(item.getGuid());
                item.setCounts(res);
                total += res;
            }
            if("3".equals(item.getIsEdit())) {
                Integer res = bmsProjectDocCatalogMapper.selectResultSimpleCounts(item.getGuid());
                item.setCounts(res);
                total += res;
            }
        }
        return total;
    }

    public String getFileSize(long fileLength) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileLength == 0) {
            return wrongSize;
        }
        if (fileLength < 1024) {
            fileSizeString = df.format((double) fileLength) + "B";
        } else if (fileLength < 1048576) {
            fileSizeString = df.format((double) fileLength / 1024) + "KB";
        } else if (fileLength < 1073741824) {
            fileSizeString = df.format((double) fileLength / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileLength / 1073741824) + "GB";
        }
        return fileSizeString;
    }
}
